package main

import (
	"encoding/json"
	"fmt"
)

/*
结构体转换成json格式
*/
type Student struct {
	ID     int
	Gender string
	name   string //私有属性 不能json包访问
	Sno    string
}

func main() {
	/*
	  结构体转换成 json  Marshal
	*/
	var s1 = Student{
		ID:     1,
		Gender: "男",
		name:   "张三",
		Sno:    "2021001",
	}
	fmt.Printf("%#v\n", s1)

	jsonByte, _ := json.Marshal(s1)
	jsonStr := string(jsonByte)
	fmt.Printf("%v---%v\n", jsonStr, jsonByte)
	/*
	  {"ID":1,"Gender":"男","Sno":"2021001"}---[123 34 73 68 34 58 49 44 34 71 101 110 100 101 114 34 58 34 231 148 183 34 44 34 78 97 109 101 34 58 34 229 188 160 228 184 137 34 44 34 83 110 111 34 58 34 50 48 50 49 48 48 49 34 125]
	*/

	/*
	   json 转换成结构体  Unmarshal
	*/

	var str = `{
		"ID":2,
		"Sno":"1123",
		"Gender":"男",
		"Name":"李四"
	}`
	var s2 Student
	err := json.Unmarshal([]byte(str), &s2)
	if err != nil {
		fmt.Println("json 转换成结构体失败", err)
	}
	fmt.Printf("%#v\n", s2)
	//main.Student{ID:2, Gender:"男", name:"", Sno:"1123"}

}
